package com.xbfinal.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xbfinal.reggie.common.R;
import com.xbfinal.reggie.pojo.Employee;
import com.xbfinal.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;


@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 登陆功能
     * 前端在请求体中带来了 两个参数
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request,
                             @RequestBody Employee employee){
        //创建request 需要把信息存入session中

        //1.把前端提交的密码进行md5 加密处理
         String password = employee.getPassword();
         password = DigestUtils.md5DigestAsHex(password.getBytes());

         //2.更具用户名查数据库
        final LambdaQueryWrapper<Employee> queryWrapper =
                new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        final Employee emp = employeeService.getOne(queryWrapper);

        //3.没查到就返回失败
        if(emp==null){
            return R.error("登陆失败，请检查用户名是否正确");
        }

        //4.密码比对(比对不成功返回错误信息)
        if(!emp.getPassword().equals(password)){
            return R.error("登陆失败，请检查密码是否正确");
        }

        //5.查看员工状态，1可用 0禁用
        if(emp.getStatus() == 0){
            return R.error("登陆失败，员工已被禁用，请联系老板");
        }
        //6.登陆成功 再把id存入session
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);


    }

    /**
     * 退出登陆
     * @return
     */
    @PostMapping("logout")
    public R<String> logout(HttpServletRequest request){

        //清理session的当前员工的id
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 新增员工
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Employee employee,
                          HttpServletRequest request){
        log.info("新增的员工信息{}",employee.toString());
        //给员工设置初始密码并加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //employee.setCreateTime(LocalDateTime.now());//创建时间
        //employee.setUpdateTime(LocalDateTime.now());//更新时间
        //Long CreateUser=(Long)request.getSession().getAttribute("employee");
        //employee.setCreateUser(CreateUser);//创建人
        //employee.setUpdateUser(CreateUser);

        final boolean save = employeeService.save(employee);
        if (save){
            return  R.success("员工新增成功");
        }
        return R.error("员工添加失败");
    }


    /**
     * 分页查询
     * /employee/page?page=1&pageSize=10
     * employee/page?page=1&pageSize=10&name=%E4%BC%98%E7%A7%80
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page ,int pageSize,String name){//泛型不能用employee、Page时分页插件带的

        log.info("page={}  pageSize={}& name={}",page,pageSize,name);
        Page pageInfo = new Page(page, pageSize);//前端传过来分页的当前码和分页的每一页的大小
        log.info("pageinfo:{}",pageInfo);

        //        构造分页构造器
    //        条件构造器
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper();
    //        添加过滤条件
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
    //        添加排序条件
        lambdaQueryWrapper.orderByDesc(Employee::getUpdateTime);
        employeeService.page(pageInfo,lambdaQueryWrapper);
        return R.success(pageInfo);
    }


    /**
     * 更具员工id修改代码(包括 禁用和编辑)
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee){

        log.info(employee.toString());
        //更新时间
        employee.setUpdateTime(LocalDateTime.now());
        //修改了逻辑
        employee.setUpdateUser((Long) request.getSession().getAttribute("employee"));
        employeeService.updateById(employee);
        return R.success("修改成功");
    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){

        final Employee employee = employeeService.getById(id);

        return R.success(employee);
    }

}
